package com.jeff.practice;

import java.util.HashSet;

public class LongestSubstring {
    public static int lengthOfLongestSubstring(String s) {
        HashSet<Character> set = new HashSet<>();
        int left = 0, right = 0; // 滑动窗口的左右边界
        int maxLength = 0; // 存储最长子串的长度

        while (right < s.length()) {
            char currentChar = s.charAt(right);
            // 如果当前字符不在集合中，加入集合并更新最长长度
            if (!set.contains(currentChar)) {
                set.add(currentChar);
                maxLength = Math.max(maxLength, right - left + 1);
                right++; // 向右移动右边界
            } else {
                // 如果当前字符在集合中，移除左边界的字符并向右移动左边界
                set.remove(s.charAt(left));
                left++;
            }
        }

        return maxLength;
    }

    public static void main(String[] args) {
        String input = "abcabcbb";
        int result = lengthOfLongestSubstring(input);
        System.out.println("无重复最长子串的长度是: " + result);
    }
}
